// pages/home-page/add-customer/addCustomer.js
const app = getApp()
import util from '../../../utils/util'
const { validateAll, validate } = require('../../../utils/validator.js')




Page({
  /**
   * 页面的初始数据
   */
  validator (rule, value, callback) {
    console.log(this)
    const reg = /^[0-9a-zA-Z]{4,20}$/
    if (value && !reg.test(value)) {
      callback(new Error('证件号码为4到20位数字和字母'))
    } else {
      callback()
    }
  },
  /**
   * 页面的初始数据
   * show 显示隐藏
   * pageList 组织数据
   * selected 已经选择的
   * quantity 有多少层0 1 2 3
   * page 第几层
   * value 取到输入框的值
   */
  data: {
    // 城市
    city: {
      show: false,
      animationData: '',
      pageList: [],
      data: [],
      name: 'city',
      title: '请选择网点',
      value: '',
      selected: [],
      index: 0,
      page: 0,
      quantity: 3
    },
    publicObj: {},
    sumitType: 'add',
    info: {
      realName: '',
      phoneNum: '',
      workNum: null,
      orgId: null
    },
    customerId: '',
    rules: {
      realName: [
        { required: true, message: '姓名必填' },
        { validator(rule, value, callback) {
            const reg = /^[a-zA-Z\u4e00-\u9fa5]{2,10}$/
            if (!reg.test(value)) {
              callback(new Error('姓名需为2-10位中文或英文字符'))
            } else {
              callback()
            }
          } },
      ],
      phoneNum: [
        { required: true, message: '手机号码必填' },
        { validator(rule, value, callback) {
          const reg = /^[0-9]{11}$/
          if (value && !reg.test(value)) {
            callback(new Error('手机号码为11位数字'))
          } else {
            callback()
          }
        } }
      ],
      workNum: [
        { required: true, message: '工号必填' },
        { validator: (rule, value, callback) => {
          console.log(this)
          const reg = /^[0-9a-zA-Z]{2,20}$/
          if (value && !reg.test(value)) {
            callback(new Error('工号为2到20位数字和字母'))
          } else {
            callback()
          }
        } },
      ],
      orgId: [
        { required: true, message: '银行网点必选' },
      ],
    },
    loading: false,
    selectedBank: []
  },



  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    if (options.info) {
      const info = JSON.parse(options.info)
      this.setData({
        'info': info,
        'sumitType': 'update',
      })
      wx.setNavigationBarTitle({
        title: '编辑理财经理',
      })
      app.api.get({
        url: 'cpic_org_getOrgLevel',
        data: {
          id: info.orgId
        }
      }).then(res => {
        const selectedBank = [
          {id: res.bank.id, select: res.bank.orgName},
          {id: res.branch.id, select: res.branch.orgName},
          {id: res.subBranch.id, select: res.subBranch.orgName},
          {id: res.site.id, select: res.site.orgName},
        ]
        this.setData({
          selectedBank
        })
        this.getBankList()
        // if (res.branch.id === app.globalData.userInfo.orgId) {
        //   const selectedBank = [
        //     {id: res.subBranch.id, select: res.subBranch.orgName},
        //     {id: res.site.id, select: res.site.orgName},
        //   ]
        //   this.setData({
        //     selectedBank
        //   })
        //   this.getBankList()
        // }
        // if (res.subBranch.id === app.globalData.userInfo.orgId) {
        //   const selectedBank = [
        //     {id: res.site.id, select: res.site.orgName},
        //   ]
        //   this.setData({
        //     selectedBank
        //   })
        //   this.getBankList()
        // }
        // if (res.site.id === app.globalData.userInfo.orgId) {
        //   const selectedBank = []
        //   this.setData({
        //     selectedBank
        //   })
        //   this.getBankList()
        // }
      })
    } else {
      this.setData({
        'sumitType': 'add'
      })
      this.getBankList()
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  inputInfo: function (e) {
    const { key } = e.currentTarget.dataset;
    const value = e.detail.value;
    this.setData({
      [`info.${key}`]: value
    })
    validate(key, this.data.rules[key], value)
  },

  
  getBankList: function () {
    console.log(233)
    app.api.post({
      url: 'userAccessableBank_getAccessableBankOrgTree',
      data: {}
    }).then(res => {
      console.log(this.data.info.id)
      if (this.data.info.id) {
        console.log(2)
        const { selectedBank } = this.data
        let curBank = res
        selectedBank.forEach((item, sIndex) => {
          curBank.some((bank, index) => {
            if (item.id === bank.id) {
              item.key = index
              sIndex !== selectedBank.length - 1 && (curBank = bank.childs)
              return true
            }
          })
        })
        this.setData({
          'city.pageList': curBank,
          'city.page': selectedBank.length - 1,
          'city.quantity': 3,
          'city.data': res,
          "city.selected": selectedBank
        })
      } else {
        console.log(5 - Number(res.depth))
        this.setData({
          'city.pageList': res,
          'city.data': res,
          'city.quantity': 3
        })
      }
    })
  },
 
  submit: function () {
    const { info } = this.data
    let flag = true
    validateAll(this.data.rules, info, (valid) => {
      if (!valid) {
        flag = false
      }
    })
    if (flag) {
      this.setData({
        loading: true
      })
      var apiUrl = this.data.sumitType == 'update' ? 'cpic_user_updateStudent' : 'cpic_user_createStudent'
      const params = {
        orgId: info.orgId,
        phoneNum: info.phoneNum,
        realName: info.realName,
        userId: info.id,
        workNum: info.workNum
      }
      app.api.post({
        url: apiUrl,
        data: params
      }).then(res =>{
        wx.navigateBack()
      }).finally(() => {
        this.setData({
          loading: false
        })
      })
    }
  },
  saveTag: function () {
    const { customerId } = this.data
    wx.navigateTo({
      url: `/pages/home-page/customer-analysis/customerAnalysis?id=${customerId}`
    })
  },
    //通过事件接收子组件传过来的参数
    city: function (event) {
      console.log(event)
      let selected = event.detail;
      this.setData({
        "city.selected": selected,
        'info.orgId': selected[event.detail.length - 1].id
      })
    },
      // 点击输入框弹出地址选择框
  cityFocus() {
    // 显示遮罩层
    var animation = wx.createAnimation({
      duration: 200,
       timingFunction: "linear",
       delay: 0
   })
   animation.translateY(600).step()
  this.setData({
    'city.animationData': animation.export()
  })
   setTimeout(function () {
    animation.translateY(0).step()
      this.setData({
        'city.animationData': animation.export()
     })
  }.bind(this), 200)
    this.setData({
      'city.show': true
    })
  },
})